<template>
  <div>
    <el-cascader
      class="wp100"
      :options="options"
      v-model="area"
      :props="props"
      clearable
      @active-item-change="handleItemChange"
      size="small"
    ></el-cascader>
  </div>
</template>

<script>
export default {
  components: {},
  props: {
    props: {
      type: Object,
      default () {
        return {
          label: 'regionName',
          value: 'id',
          children: 'children'
        }
      }
    },
    value: {
      type: Array,
      default () {
        return []
      }
    },
    showCity: {
      type: Boolean,
      default: true
    },
    showArea: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      options: [],
      provinceIndex: -1,
      cityIndex: -1
    }
  },
  computed: {
    area: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {},
  async created () {
    this.options = await this.getList(1, '', 1)
  },
  methods: {
    async getList (regionLevel = 1, pId, hasChildren) {
      let _res = await this.$apis.region.getRegionList({ regionLevel, pId })
      if (hasChildren) {
        let obj = {}
        obj[this.props['children']] = []
        return _res.map(item => {
          return {
            ...item,
            ...obj
          }
        })
      }
      return _res
    },
    async handleItemChange (value) {
      let res
      let obj = {}
      let children = this.props['children']
      if (value.length === 1 && this.showCity) {
        this.provinceIndex = this.options.findIndex(
          item => item.id === value[0]
        )
        res = await this.getList(value.length + 1, value[0], 1)
        obj[children] = res
        this.$set(this.options, this.provinceIndex, {
          ...this.options[this.provinceIndex],
          ...obj
        })
      } else if (value.length === 2 && this.showCity && this.showArea) {
        this.cityIndex = this.options[this.provinceIndex][children].findIndex(
          item => item.id === value[1]
        )
        res = await this.getList(value.length + 1, value[1], 0)
        if (!res.length) {
          delete this.options[this.provinceIndex][children][this.cityIndex][children]
        } else {
          this.options[this.provinceIndex][children][this.cityIndex][children] = res
        }
      }
    },
    activeItemChange (e) {
    }
  }
}
</script>
